<template>
  <a-card>
    <a-row :gutter="24">
      <a-col :md="6" :sm="24">
        <a-card hoverable style="height:600px;overflow-y:auto">
          <a-tree :showLine="true" @expand="onExpand" :expandedKeys="expandedKeys" :autoExpandParent="autoExpandParent" v-model="checkedKeys" @select="onSelect" :selectedKeys="selectedKeys" :treeData="treeData" :replaceFields="replaceFields" />
        </a-card>
      </a-col>
      <a-col :md="18" :sm="24">
        <div class="table-page-search-wrapper" style="margin-bottom:16px">
          <a-row style="margin-bottom:16px">

            <a-col :md="8" :sm="24" style="text-align:right">
              <a-button type="primary" class="actionButton" @click="add">添加</a-button>
              <a-popconfirm title="确定删除?" okText="确定" cancelText="取消" @confirm="del">
                <a-button type="danger" class="actionButton">删除</a-button>
              </a-popconfirm>
            </a-col>
          </a-row>
        </div>
        <a-spin :spinning="spinning" tip="获取数据中...">
          <div class="spin-content">
            <a-table size="small" bordered :rowKey="record => record.id" :columns="columns" :pagination="pagination" :dataSource="data" :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }" :rowClassName="setRowClassName">
              <span slot="action" slot-scope="text, record">
                <template>
                  <a-tooltip placement="top">
                    <template slot="title">
                      <span>修改</span>
                    </template>
                    <span size="small" type="link" @click="handleEdit(record)" style="cursor:pointer;color:#1890FF">修改</span>
                  </a-tooltip>
                </template>
              </span>
            </a-table>
          </div>
        </a-spin>
      </a-col>
    </a-row>
    <a-modal :title="title" :visible="visible" @cancel="handleCancel" :footer="null" :centered="true">
      <div class="waterArea" style="background-color:#fff">
        <a-spin :spinning="loading">
          <a-form :form="form">
            <a-form-item v-bind="formItemLayout" label="类别名称">
              <a-input v-decorator="['CategoryName', { rules: [{ required: true, message: '请填写部门编码!' }] }]" />
            </a-form-item>
            <a-form-item v-bind="formItemLayout" label="类别类型">
              <a-select v-decorator="['CategoryType', { rules: [{ required: true, message: '请填写部门名称!' }] }]" size="small" style="width: 100%;" @change="getType">
                <a-select-option :value="1">分类</a-select-option>
                <a-select-option :value="2">链接</a-select-option>
                <a-select-option :value="3">图文</a-select-option>
              </a-select>
              <!-- <a-input v-decorator="['CategoryType', { rules: [{ required: true, message: '请填写部门名称!' }] }]" /> -->
            </a-form-item>
            <a-form-item v-bind="formItemLayout" label="上级分类">
              <treeselect :show-count="true" :options="Dept" v-model="ParentId" placeholder="请选择" :normalizer="normalizer" />
            </a-form-item>
            <a-form-item v-bind="formItemLayout" label="层次级别">
              <a-input v-decorator="['Level', { rules: [{ required: true, message: '请填写排序!' }] }]" />
            </a-form-item>
            <a-form-item v-bind="formItemLayout" label="链接URL" v-if="productType == 2">
              <a-input v-decorator="['LinkUrl', { rules: [{ required: true, message: '链接URL!' }] }]" />
            </a-form-item>
            <a-form-item v-bind="formItemLayout" label="类别图片">
              <!-- <a-input v-decorator="['ImageUrl', { rules: [{ required: true, message: '类别图片URL!' }] }]" /> -->
              <a-upload name="avatar" listType="picture-card" class="avatar-uploader" :showUploadList="false" :action="uploarUrl" :headers="headers" :beforeUpload="beforePhotoUpload" @change="handlePhotoChange">
                <a-popover placement="right">
                  <template slot="content">
                    <a-button @click="removePhotoUrl" type="danger" size="small">删除</a-button>
                    <a-button @click="viewPhoto(1)" type="primary" style="margin-left:5px" size="small">查看大图</a-button>
                  </template>
                  <img v-if="PhotoUrl" style="height:104px" :src="PhotoUrl" alt="avatar" />
                </a-popover>
                <div v-if="!PhotoUrl">
                  <a-icon :type="Photoloading ? 'loading' : 'plus'" />
                  <div class="ant-upload-text">图片上传</div>
                </div>
              </a-upload>
            </a-form-item>
            <a-form-item v-bind="formItemLayout1" style="text-align:center;margin-bottom:0">
              <a-button type="primary" @click="ok">确定</a-button>
            </a-form-item>
          </a-form>
        </a-spin>
      </div>
    </a-modal>

  </a-card>
</template>
  
  <script>
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'

import { getCategoryTree, getCategoryList, deleteCategory, getCategoryDetail, saveCategory } from '@/api/category';
import { deleteChildrenIfNull, typleFilter } from '@/utils/util'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import '@/views/treeselect1.css'
import { authDevice } from '@/utils/mixin'
import { getImg } from '@/api/students'

import moment from 'moment'
export default {
  mixins: [authDevice],
  components: {
    Treeselect
  },
  data () {
    return {
      title: '添加部门',
      visible: false,
      visibleDepart: false,
      expandedKeys: [],
      autoExpandParent: true,
      productType: '',
      checkedKeys: [],
      selectedKeys: [],
      treeData: [],
      data: [],
      queryParam: {
        index: 1,
        pageSize: 10,
        ParentId: ''
      },
      Photoloading: false,
      PhotoUrl: '',
      PhotoUrlDb: {},
      PhotoUrlDbString: '',
      headers: {
        authorization: '',
      },
      uploarUrl: process.env.VUE_APP_API_BASE_URL + `/api/Upload/uploadImg?tablename=StudentInfo&signname=Photo`,
      selectedRowKeys: [],
      replaceFields: {
        key: 'id',
        children: 'Children',
        title: 'CategoryName'
      },
      normalizer (node) {
        return {
          id: node.id,
          label: node.CategoryName,
          children: node.Children
        }
      },
      spinning: false,
      // 表头
      columns: [
        {
          title: '分类名称',
          dataIndex: 'CategoryName',
          key: 'CategoryName',
          align: 'center'
        },
        {
          title: '分类类别',
          dataIndex: 'CategoryTypeName',
          key: 'CategoryTypeName',
          align: 'center'
        },
        {
          title: '排序',
          dataIndex: 'Level',
          key: 'Level',
          align: 'center'
        },
        {
          title: '添加时间',
          dataIndex: 'AddTime',
          key: 'AddTime',
          align: 'center'
        },
        {
          title: '操作',
          width: '150px',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' },
          align: 'center'
        }
      ],

      pagination: {
        onChange: (index, pageSize) => {
          this.pageOnChange(index, pageSize)
        },
        current: 1,
        total: 0,
        showQuickJumper: true,
        size: 'small',
        defaultPageSize: 10,
        showTotal: (total) => `共 ${total} 条数据`,
        showSizeChanger: true,
        pageSizeOptions: ['5', '10', '15', '20'],
        onShowSizeChange: (index, pageSize) => {
          this.pageOnChange(index, pageSize)
        },
        position: 'bottom',
      },
      loading: false,
      form: this.$form.createForm(this),
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 18 }
        }
      },
      formItemLayout1: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 0 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 }
        }
      },
      Dept: [],
      currentId: null,
      ParentId: null
    }
  },
  watch: {
    checkedKeys (val) {
      console.log('onCheck', val)
    }
  },
  created () {
    this.initTree()
    this.initData(null)
  },
  methods: {

    //当切换分类商品类型的时候,得到他的值
    getType () {
      this.$nextTick(() => {
        console.log('form:{}', this.form.getFieldValue('CategoryType'));
        this.productType = this.form.getFieldValue('CategoryType')
      });
    },
    initTree () {
      getCategoryTree().then(res => {

        this.Dept = res.data
        this.removeChildrenIfNUll(this.Dept)
        this.treeData = res.data
      })
    },
    removeChildrenIfNUll (data) {
      data?.map(a => {
        if (a && a.Children.length > 0) {
          this.removeChildrenIfNUll(a.Children)
        } else {
          deleteChildrenIfNull(a)
        }
      })
    },
    initData (data) {
      this.spinning = true
      getCategoryList({ parentID: data || '', ...this.queryParam })
        .then(res => {
          const { data, page } = res
          this.data = data && data.length > 0 ? data.map(el => {
            return {
              ...el,
              CategoryTypeName: typleFilter(el.CategoryType),
              AddTime: el.AddTime ? moment(el.AddTime).format('YYYY-MM-DD HH:mm:ss') : ''
            }
          }) : []
          this.pagination.total = page.RecordCount
        })
        .finally(() => {
          this.spinning = false
        })
    },
    search () {
      this.initData(null)
    },
    pageOnChange (index, pageSize) {
      this.spinning = true
      console.log(this.queryParam)
      Object.assign(this.pagination, {
        current: index,
        pageSize,
        index,
      })
      Object.assign(this.queryParam, {
        pageSize,
        index,
      })
      this.initData(null)
    },
    add () {
      this.title = '添加部门'
      this.visible = true
      this.form.resetFields()
      this.ParentId = null
      this.PhotoUrlDb = ''
        this.PhotoUrl = ''
        this.PhotoUrlDbString = ''
    },
    ok () {
      const {
        form: { validateFields }
      } = this
      validateFields((errors, values) => {
        if (!errors) {
          this.loading = true
          setTimeout(() => {
            // console.log(this.$store.getters.token.id)
            const value = {
              ...values,
              Id: this.currentId,
              ParentId: this.ParentId,
              ImageUrl: this.PhotoUrl
            }
            saveCategory(value).then(res => {
              this.initData(this.selectedKeys[0])
              this.initTree()
              this.currentId = null
              this.loading = false
              this.visible = false
            })
          }, 1000)
        } else {
        }
      })
    },
    okDepart () {
      this.visibleDepart = false
    },
    del () {
      if (!(this.selectedRowKeys && this.selectedRowKeys.length > 0)) {
        this.$message.warning('请选择数据')
        return
      }
      deleteCategory(this.selectedRowKeys).then(res => {
        this.initData(this.selectedKeys[0])
        this.initTree()
        this.selectedRowKeys = []
      })
    },
    open () {
      this.visibleDepart = true
    },
    handleEdit (data) {
      this.title = '修改分类'
      this.productType = data.CategoryType
      getCategoryDetail({ categoryID: data.id }).then(res => {
        this.visible = true
        setTimeout(() => {
          this.ParentId = data.ParentID
          this.currentId = data.id
          this.form.setFieldsValue({ CategoryName: data.CategoryName })
          this.form.setFieldsValue({ CategoryType: data.CategoryType })
          this.form.setFieldsValue({ Level: data.Level })

          this.form.setFieldsValue({ LinkUrl: data.LinkUrl })
          this.form.setFieldsValue({ ImageUrl: data.ImageUrl || '' })
          this.PhotoUrlDbString = data.ImageUrl
          this.PhotoUrl = data.ImageUrl
        }, 500)
      })
    },
    onSelectChange (selectedRowKeys) {
      console.log('selectedRowKeys changed: ', selectedRowKeys)
      this.selectedRowKeys = selectedRowKeys
    },
    onExpand (expandedKeys) {
      console.log('onExpand', expandedKeys)
      // if not set autoExpandParent to false, if children expanded, parent can not collapse.
      // or, you can remove all expanded children keys.
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    onCheck (checkedKeys) {
      console.log('onCheck', checkedKeys)
      this.checkedKeys = checkedKeys
    },
    onSelect (selectedKeys, e) {
      this.ParentId = e.selectedNodes[0].data.props.name
      // this.form.setFieldsValue({ ParentName: this.ParentName })
      console.log(this.ParentId)
      this.selectedKeys = selectedKeys
      this.ParentId = selectedKeys[0]
      console.log(selectedKeys[0])
      this.initData(selectedKeys[0])
    },
    handleCancel () {
      this.productType = undefined
      this.visible = false
    },
    handleCancelDepart () {
      this.visibleDepart = false
    },
    setRowClassName (record, idx) {
      return idx % 2 == 1 ? 'bg-row' : ''
    },
    viewPhoto (data) {
      this.$refs.photomodal.view(data)
    },
    beforePhotoUpload (file) {
      const token = Vue.ls.get(ACCESS_TOKEN) && Vue.ls.get(ACCESS_TOKEN).token
      this.headers = {
        authorization: 'Bearer ' + token
      }
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        this.$message.error('您只能上传JPG或PNG!')
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('必须小于2MB!')
      }
      // console.log('')
      return isJpgOrPng && isLt2M
    },
    viewPhoto (data) {
      this.$refs.photomodal.view(this.PhotoUrl)
    },
    handlePhotoChange (info) {
      if (info.file.status === 'error') {
        this.$message.error(`上传失败`)
      }
      if (info.file.status === 'uploading') {
        this.Photoloading = true
        return
      }
      if (info.file.status === 'done') {
        this.PhotoUrlDb = info.file.response
        this.PhotoUrl = getImg(`${this.PhotoUrlDb.Path}/${this.PhotoUrlDb.NewFileName}`)
        this.PhotoUrlDbString = `${this.PhotoUrlDb.Path}/${this.PhotoUrlDb.NewFileName}`
        this.Photoloading = false
      }
    },
    removePhotoUrl () {
      this.PhotoUrl = null
      this.PhotoUrlDb = null
      this.PhotoUrlDbString = null
    },
  }
}
  </script>
  
  <style lang="less" scoped>
.actionButton {
  margin-right: 10px;
}

.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
.tree-select-label-YH {
  display: inline-block;
  height: 30px;
  vertical-align: bottom;
  text-align: right;
}
.tree-select-self-YH {
  display: inline-block;
  width: 200px;
  margin-left: 8px;
}
</style>
  